import React, { FC } from 'react';
import { FormPanel, InputType, type FormPanelObject, FormPanelBtnAlign, Utils } from 'lfun-bg-comp';
import { Breadcrumb, Button, Table, TableProps, Space } from 'antd';
import _ from 'lodash';
import { useLocation, useNavigate } from 'react-router-dom';
import { PageContainer } from '@/component/page-container';
import { KG_LEVEL, FOUNDER_TYPE, SCHOOL_OPERATION_TYPE } from '@/constant/schoolOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import utils, { buildPageItemTxtByEduType, getPagePath, getPathRoot, get_stoge_pz, set_stoge_pz } from '@/utils';
import styles from './index.less';
import { SearchSchool, getSchoolAudit } from '@/service/unit/school';
import { APPROVAL_STATUS } from '@/constant';
import useCountry from '@/hooks/useCountry';
import { isPermissionOperate } from '@/component/permission-button';

const Groups: FC = () => {
  //const [current, setCurrent] = React.useState();
  const [dataSource, setDataSource] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState(null);
  const [tableLoading, setTableLoading] = React.useState(false);
  const location = useLocation();
  const country = useCountry();

  const navigate = useNavigate();
  const list: FormPanelObject[] = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: buildPageItemTxtByEduType('园所名称'),
          name: 'school_name',
          key: 'school_name',
          textRange: [0, 20],
        },
        {
          label: '举办者类型',
          name: 'founder_type',
          key: 'founder_type',
          inputType: InputType.cascader,
          inputProps: {
            multiple: true,
          },
          renderOption: FOUNDER_TYPE,
        },
        {
          label: '行政管辖区',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '地域管辖区',
          name: 'block',
          key: 'block',
          inputType: InputType.select,
          renderOption: country,
        },
        //   {
        //     label: '状态',
        //     name: 'status',
        //     key: 'status',
        //     inputType: InputType.select,
        //     renderOption: KG_ORDER_STATUS,
        //   },
        {
          label: '状态',
          name: 'appoval_status',
          key: 'appoval_status',
          inputType: InputType.select,
          renderOption: APPROVAL_STATUS,
        },
        {
          label: buildPageItemTxtByEduType('园所代码'),
          name: 'school_code',
          key: 'school_code',
          textRange: [0, 20],
        },
        {
          label: '星级',
          name: 'school_level',
          key: 'school_level',
          inputType: InputType.select,
          renderOption: KG_LEVEL,
          hidden: Utils.getProps('edu_type') !== 'kg',
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '编号',
      width: 100,
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      fixed: 'left',
      render(val, row, index) {
        return index + 1;
      },
    },
    {
      title: buildPageItemTxtByEduType('园所代码'),
      width: 100,
      dataIndex: 'school_no',
      key: 'school_no',
      align: 'center',
      fixed: 'left',
    },
    {
      title: buildPageItemTxtByEduType('园所名称(分校)'),
      width: 500,
      dataIndex: 'school_name',
      key: 'school_name',
      align: 'center',
      fixed: 'left',
    },
    {
      title: '行政管辖区',
      width: 150,
      dataIndex: 'borough',
      key: 'borough',
      align: 'center',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '地域管辖区',
      width: 150,
      dataIndex: 'block',
      key: 'block',
      align: 'center',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '举办者类型',
      width: 300,
      dataIndex: 'founder_type',
      key: 'founder_type',
      align: 'center',
      render: (text: any) => {
        let arr: any[] = [];
        if (_.isArray(text)) {
          arr = text.map(v => utils.findLabelDeep(FOUNDER_TYPE, String(v)));
        }
        return arr.join('-');
      },
    },
    {
      title: buildPageItemTxtByEduType('园所星级'),
      width: 100,
      dataIndex: 'school_level',
      key: 'school_level',
      align: 'center',
      render: (text: any) => {
        return _.find(KG_LEVEL, { value: String(text) })?.label;
      },
    },
    // {
    //   title: '办学类型',
    //   width: 100,
    //   dataIndex: 'school_operation_type',
    //   key: 'school_operation_type',
    //   align: 'center',
    //   render: (text: any) => {
    //     let arr: any[] = [];
    //     if (_.isArray(text)) {
    //       arr = text.map(v => utils.findLabelDeep(SCHOOL_OPERATION_TYPE, String(v)));
    //     }
    //     return arr.join('-');
    //   },
    // },
    {
      title: '教育层次',
      dataIndex: 'school_edu_level',
      key: 'school_edu_level',
      align: 'center',
      width: 100,
      render: (text: any) => {
        return _.find(SCHOOL_OPERATION_TYPE, { value: String(text) })?.label;
      },
    },
    {
      title: '学校（机构）类别',
      dataIndex: 'school_category',
      key: 'school_category',
      align: 'center',
      width: 200,
      render: (text: any, record: any) => {
        const res = _.find(SCHOOL_OPERATION_TYPE, { value: record.school_edu_level });
        if (res) {
          return _.find(res.children, { value: String(text) })?.label;
        }
        return text;
      },
    },
    {
      title: '办学类型',
      dataIndex: 'school_operation_type',
      key: 'school_operation_type',
      width: 100,
      align: 'center',
      render: (text: any, record: any) => {
        const edu_level_res = _.find(SCHOOL_OPERATION_TYPE, { value: record.school_edu_level });
        if (edu_level_res) {
          const res = _.find(edu_level_res.children, { value: String(record.school_category) });
          if (res) {
            return _.find(res.children, { value: String(text) })?.label;
          }
        }
        return text;
      },
    },
    {
      title: '状态',
      dataIndex: 'approval_status',
      width: 100,
      key: 'approval_status',
      align: 'center',
      render: (text: any) => {
        return _.find(APPROVAL_STATUS, { value: text })?.label;
      },
    },
    {
      title: '审核说明',
      dataIndex: 'appoval_reson',
      key: 'appoval_reson',
      width: 200,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'op',
      key: 'op',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Space>
            <Button
              key="look"
              type="link"
              size="small"
              onClick={() => {
                navigate(`${getPathRoot()}/school-audit/${getProcess_path()}/details/${record.school_id}`, {
                  state: { ...record },
                });
              }}
            >
              查看
            </Button>
            {['pending', 'progressing'].includes(record.approval_status) && (
              <Button
                type="link"
                size="small"
                onClick={() =>
                  navigate(`${getPathRoot()}/school-audit/${getProcess_path()}/details/${record.school_id}`, {
                    state: { ...record },
                  })
                }
              >
                审核
              </Button>
            )}
          </Space>
        );
      },
      align: 'center',
    },
  ];
  const getProcess_code = () => {
    const path = location.pathname;
    if (path.includes('school-audit/openschool')) {
      return 's_school_open';
    }
    if (path.includes('school-audit/closeschool')) {
      return 's_school_close';
    }
    if (path.includes('school-audit/changekeyinfo')) {
      return 's_school_keyinfo_change';
    }
    return '';
  };
  const getProcess_path = () => {
    return {
      s_school_open: 'openschool',
      s_school_close: 'closeschool',
      s_school_keyinfo_change: 'changekeyinfo',
    }[getProcess_code()];
  };
  const search = async (params: any, pageSize, pageIndex) => {
    if (tableLoading) {
      return;
    }
    setTableLoading(true);
    const searchParams: SearchSchool = {
      ...params,
      process_code: getProcess_code(),
    };
    if (params && params.founder_type && params.founder_type.length > 0) {
      const fouder_type_set1 = new Set<string>();
      const fouder_type_set2 = new Set<string>();
      const fouder_type_set3 = new Set<string>();
      params.founder_type.forEach(item => {
        if (item.length > 2) fouder_type_set3.add(item[2]);
        else if (item.length > 1) fouder_type_set2.add(item[1]);
        else if (item.length > 0) fouder_type_set1.add(item[0]);
      });
      searchParams.founder_type = Array.from(fouder_type_set1);
      searchParams.founder_type_lv2 = Array.from(fouder_type_set2);
      searchParams.founder_type_lv3 = Array.from(fouder_type_set3);
    }
    const { success, data } = await getSchoolAudit(searchParams, pageIndex, pageSize);
    if (success) {
      setDataSource(
        data?.items?.map((v, i) => {
          v.key = i;
          v.founder_type = [v.founder_type, v.founder_type_lv2, v.founder_type_lv3];
          v.planning_school_operation_type = [
            v.planning_school_operation_type,
            v.planning_school_operation_type_lv2,
            v.planning_school_operation_type_lv3,
          ];
          return v;
        })
      );
      setTotal(data.total);
      setPageSize(pageSize);
      setPageIndex(pageIndex);
      setTableLoading(false);
    }
  };

  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(form?.getFieldsValue(), pageSize, pageIndex);
  };

  React.useEffect(() => {
    search({}, pageSize, 1);
    //return () => {};
  }, [location.pathname]);

  return (
    <PageContainer header={<Breadcrumb items={[{ title: getPagePath().power_name }]} />}>
      <FormPanel
        template={list}
        key={1}
        btnsAlign={FormPanelBtnAlign.right}
        //buttons={buildBtns()}
        submitBtnText="搜索"
        restBtnText="重置"
        onFinish={(formPanelObject: FormPanelObject) => {
          const params = formPanelObject.getFieldsValue();
          search(params, pageSize, 1);
          setForm(form);
          return false;
        }}
      />
      <Table
        loading={tableLoading}
        className={styles.table}
        dataSource={dataSource?.map((v, idx) => {
          v.key = idx;
          return v;
        })}
        scroll={{ x: 'max-content' }}
        columns={Utils.getProps('edu_type') === 'kg' ? columns : columns.filter(it => it.key !== 'school_level')}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
    </PageContainer>
  );
};

export default Groups;
